package com.kyivmohyla.kma2.dao;

import com.kyivmohyla.kma2.dao.mapper.PositionRowMapper;
import com.kyivmohyla.kma2.model.Position;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import java.util.List;

public class PositionDaoJdbc extends JdbcDaoSupport implements PositionDao {

    @Override
    public Position getById(int id) throws DataAccessException {
        return getJdbcTemplate()
                .queryForObject(
                        "SELECT position.position_id, position.name FROM position WHERE position.position_id = ?",
                        new Object[]{id}, new PositionRowMapper());
    }

    @Override
    public List<Position> getAll() throws DataAccessException {
        return getJdbcTemplate()
                .query("SELECT position.position_id, position.name FROM position ORDER BY position.position_id",
                        new PositionRowMapper());
    }

    @Override
    public void create(Position position) throws DataAccessException {
        getJdbcTemplate()
                .update("INSERT INTO position (position.position_id, position.name) VALUES (position_seq.NEXTVAL, ?)",
                        position.getName());
    }

    @Override
    public void update(Position position) throws DataAccessException {
        getJdbcTemplate()
                .update("UPDATE position SET position.name = ? WHERE position.position_id = ?",
                        position.getName(),
                        position.getPositionId());
    }

    @Override
    public void delete(Position position) throws DataAccessException {
        getJdbcTemplate().update(
                "DELETE FROM position WHERE position.position_id = ?",
                position.getPositionId());
    }

}
